package com.ofo.ajax;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.google.gson.Gson;
import com.ofo.model.Marks;
import com.ofo.model.TextMsg;
import com.ofo.services.IndexActionServices;
import com.ofo.util.MyStringUtil;
import com.opensymphony.xwork2.ActionSupport;

@Scope("prototype")
@Controller
public class WxAjax extends ActionSupport
		implements ServletRequestAware, SessionAware, ApplicationAware, ServletResponseAware {
	private static final long serialVersionUID = 1L;
	private HttpServletRequest request;
	private Map<String, Object> session;
	private Map<String, Object> application;
	private HttpServletResponse response;
	private Integer marksId;
	private String password;
	private HashMap<String, Object> otherData = new HashMap<String, Object>();// 临时数据储存

	@Resource(name = "indexActionServices")
	private IndexActionServices indexActionServices;

	public void getWxInfo() throws IOException {
		// StringBuffer sb = new StringBuffer();
		// InputStream is1 = request.getInputStream();
		// InputStreamReader isr = new InputStreamReader(is1, "UTF-8");
		// BufferedReader br = new BufferedReader(isr);
		// String s = "";
		// while ((s = br.readLine()) != null) {
		// sb.append(s);
		// }
		// String xml = sb.toString(); //次即为接收到微信端发送过来的xml数
		// System.out.println(xml);

		String signature = request.getParameter("echostr");
		if (signature != null) {
			String token = "xwintop";
			String timestamp = request.getParameter("timestamp");
			String nonce = request.getParameter("nonce");
			String echostr = request.getParameter("echostr");
			// // temp:临时打印，观看返回参数情况
			System.out.println(
					":signature:" + signature + ",timestamp:" + timestamp + ",nonce:" + nonce + ",echostr:" + echostr);
			// 第一步:将token、timestamp、nonce三个参数进行字典序排序
			String[] parms = new String[] { token, timestamp, nonce };// 将需要字典序排列的字符串放到数组中
			Arrays.sort(parms);// 按照api要求进行字典序排序
			// 第二步:将三个参数字符串拼接成一个字符串进行sha1加密
			// 拼接字符串
			String parmsString = "";// 注意，此处不能=null。
			for (int i = 0; i < parms.length; i++) {
				parmsString += parms[i];
			}
			// sha1加密
			String mParms = null;// 加密后的结果
			MessageDigest digest = null;
			try {
				digest = java.security.MessageDigest.getInstance("SHA");
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			digest.update(parmsString.getBytes());
			byte messageDigest[] = digest.digest();
			// Create Hex String
			StringBuffer hexString = new StringBuffer();
			// 字节数组转换为 十六进制 数
			for (int i = 0; i < messageDigest.length; i++) {
				String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexString.append(0);
				}
				hexString.append(shaHex);
			}
			mParms = hexString.toString();// 加密结果

			/*
			 * api要求： 若确认此次GET请求来自微信服务器，请原样返回echostr参数内容， 则接入生效， 成为开发者成功，否则接入失败。
			 */
			// 第三步： 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信接入成功。
			// System.out.println(TAG + ":" + mParms + "---->" + signature);
			if (mParms.equals(signature)) {
				// System.out.println(TAG + ":" + mParms + "---->" + signature);
				printString(echostr);
				return;
			} else {
				// 接入失败,不用回写
				// System.out.println(TAG + "接入失败");
			}
		}
		/*
		 * 该部分我们获取用户发送的信息，并且解析成<K,V>的形式进行显示
		 */
		// 解析用户发送过来的信息
		InputStream is = request.getInputStream();// 拿取请求流
		// 将解析结果存储在HashMap中
		Map<String, String> map = new HashMap<String, String>();
		// 解析xml，将获取到的返回结果xml进行解析成我们习惯的文字信息
		SAXReader reader = new SAXReader();// 第三方jar:dom4j【百度：saxreader解析xml】
		Document document = null;
		try {
			document = reader.read(is);
		} catch (DocumentException e1) {
			e1.printStackTrace();
		}
		// 得到xml根元素
		Element root = document.getRootElement();
		// 得到根元素的所有子节点
		List<Element> elementList = root.elements();
		// 遍历所有子节点
		for (Element e : elementList) {
			map.put(e.getName(), e.getText());
		}
		Set<String> keySet = map.keySet();
		for (String key : keySet) {
			System.out.println(key + ":" + map.get(key));
		}

		String content = map.get("Content").trim();
		try {
			if (content.contains("+")) {
				String[] str = content.split("\\+");
				boolean isTrue = false;
				if (str[0].length() >= 4 && str[0].length() <= 7 && str[1].length() >= 4) {
					isTrue = indexActionServices.addMarks(Integer.parseInt(str[0]), str[1], "xwintop");
				}
				if (isTrue) {
					content = "收录成功，感谢您的分享^_^";
				} else {
					content = "收录发生异常，请检查您输入的车牌号及密码（系统可能已经收录，谢谢）^_^";
				}
			} else if (Integer.parseInt(content) != 0) {
				Marks marks = indexActionServices.getMarks(Integer.parseInt(content));
				if (marks != null) {
					otherData.put("marks", marks);
					content = "车牌：" + content + "\n密码为：" + marks.getBikePasswords().get(0).getPassword();
				} else {
					content = "暂未收录该车密码,欢迎分享您解锁后的密码,方便大家使用，谢谢^_^\n回复【车牌号+密码】即可分享密码。如：123456+1234";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			content = "欢迎访问追风的博客\n\n请输入的车牌号获取密码\n\n<a href=\"http://www.xwintop.com\">点击进入追风的博客</a>\n\n<a href=\"http://ofo.xwintop.com\">点击进入小黄车密码共享平台</a>";
		}
		// 实例1：发送普通文本消息,请查看文档关于“回复文本消息”的xml格式
		// // 第一步：按照回复文本信息构造需要的参数
		TextMsg textMsg = new TextMsg();
		textMsg.setToUserName(map.get("FromUserName"));// 发送和接收信息“User”刚好相反
		textMsg.setFromUserName(map.get("ToUserName"));
		textMsg.setCreateTime(System.currentTimeMillis());// 消息创建时间 （整型）
		textMsg.setMsgType("text");// 文本类型消息
		textMsg.setContent(content);
//		System.out.println(textMsg);
		printString(textMsg);
	}

	/*
	 * 向页面输出
	 */
	private void printString(Object str) {
		response.setContentType("html/text;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		out.print(str);
		out.close();
	}

	public Integer getMarksId() {
		return marksId;
	}

	public void setMarksId(Integer marksId) {
		this.marksId = marksId;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Map<String, Object> getSession() {
		return session;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public Map<String, Object> getApplication() {
		return application;
	}

	public void setApplication(Map<String, Object> application) {
		this.application = application;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public HashMap<String, Object> getOtherData() {
		return otherData;
	}

	public void setOtherData(HashMap<String, Object> otherData) {
		this.otherData = otherData;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

}
